package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.service.CategoryService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Auther: 宋H
 * @Date: 2022/9/6
 * @Description: com.itheima.controller
 * @version: 1.0
 */
@RestController
@Slf4j
@RequestMapping("/category")
@Api(tags="菜品分类相关接口")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R<String> categorySave(@RequestBody Category category){
        log.info("新增菜品分类，{}",category);

        if(category!=null){
            categoryService.save(category);
            return R.success("新增菜品分类成功");
        }
        return R.error("未知错误");
    }

    /**
     * 分类管理页面分页展示
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> categorySave(int page,int pageSize){
        log.info("菜品分类分页");
        Page<Category> pageInfo=new Page<>(page,pageSize);

        //创建条件构造器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        //添加排序条件，根据sort升序排序
        lqw.orderByAsc(Category::getSort);
        categoryService.page(pageInfo, lqw);
        return R.success(pageInfo);
    }

    /**
     *  查询菜品分类Id,删除指定菜品分类
     * @param ids
     * @return {@link R< String>}
     */
    @DeleteMapping
    public R<String> categoryDelete(Long ids){
        log.info("删除菜品分类,{}",ids);

        categoryService.remove(ids);
        return R.success("分类信息删除成功");
    }

    /**
     * 修改菜品分类
     * @param category
     * @return {@link com.itheima.controller.R<java.lang.String>}
     */
    @PutMapping
    public R<String> categoryUpdate(@RequestBody Category category){
        log.info("修改分类,{}",category);

        categoryService.updateById(category);
        return R.success("分类信息修改成功");
    }

    /**
     * 根据条件查询分类数据
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> categoryList(Category category){
        log.info("查询菜品分类列表,{}",category);
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(category.getType()!=null,Category::getType,category.getType());
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(lqw);
        return R.success(list);
    }
}
